package arrayobjectexercise;

public class Test {
    public static void main(String[] args){
        //1.创建一个数组来存储游戏装备对象
        GameEquipment[] arr = new GameEquipment[3];
        //2.创建游戏装备对象并添加到数组中
        GameEquipment game1 = new GameEquipment(1,"石剑",5,100);
        GameEquipment game2 = new GameEquipment(2,"铁剑",10,1000);

        //3.把游戏准备对象添加到数组当中
        arr[0] = game1;
        arr[1] = game2;

        //再次添加一个游戏装备对象，并在添加的时候进行id的唯一性判断。
        GameEquipment game3 = new GameEquipment(3,"钻石剑",20,5000);
        boolean flag = contains(arr, game3.getId());
        if(flag){
            System.out.println("当前id重复，请修改id后再进行添加");
        }else{
            int count = getCont(arr);
            if(count == arr.length){
                GameEquipment[] newArr = creatNewArr(arr);
                newArr[count] = game3;
                printArr(arr);
            }else {
                arr[count] = game3;
                printArr(arr);
            }
        }

    }

    public  static void printArr(GameEquipment[] arr){
        for (int i = 0;i <arr.length; i++){
            GameEquipment game = arr[i];
            if(game != null){
                System.out.println("id: " + game.getId() +" 名称：" + game.getName() + " 攻击力：" + game.getAttackPower() + " 价格：" + game.getPrice());
            }
        }
    }

    public static GameEquipment[] creatNewArr(GameEquipment[] arr){
        GameEquipment[] newArr = new GameEquipment[arr.length + 1];
        for (int i = 0; i< arr.length; i++){
            newArr[i] = arr[i];
        }
        return  newArr;
    }
    public static  int getCont(GameEquipment[] arr){
        int count = 0;
        for (int i= 0; i < arr.length; i++){
            if(arr[i] != null){
                count++;
            }
        }
        return count;
    }

    public static boolean contains(GameEquipment[] arr, int id){
        for (int i = 0; i < arr.length; i++){
            //依次获取到数组里面的每一个游戏装备对象
            GameEquipment game = arr[i];
            if(game != null){
                //获取数组中游戏装备对象的id
                int sid = game.getId();
                //比较
                if(sid == id){
                    return  true;
                }
            }
        }
        //当循环结束之后，还没有找到一样的，那么就表示数组中要查找的id是不存在的。
        return false;
    }


}
